﻿using System;
using System.Collections.Generic;
using System.Configuration;
using FunctionalCLR.Core;
using FunctionalCLR.Core.Function;

namespace FunctionalCLR.Shell {
    public class ContextFunctionManager : DefaultFunctionManager {

        public IContext Context {
            get;
            set;
        }

        public ContextFunctionManager(IContext context)
            : base() {
            this.Context = context;
        }

        public override void Add(string funcName, object func) {
            if (func is ContextFuncNode) {
                ContextFuncNode cfn = func as ContextFuncNode;
                cfn.Context = this.Context;
            }

            base.Add(funcName, func);
        }

        public override FuncNode Get(string functionName) {
            FuncNode fn = base.Get(functionName);

            if (fn is UserDefinedFunctionNode) {
                UserDefinedFunctionNode udf = fn as UserDefinedFunctionNode;
                UserDefinedFunctionNode newUdf
                    = new UserDefinedFunctionNode();
                newUdf.Name = udf.Name;
                newUdf.FuncBody = udf.FuncBody;
                newUdf.Comment = udf.Comment;
                newUdf.FunctionManager = udf.FunctionManager;
                newUdf.Parameters = new string[udf.Parameters.Length];
                for (int index = 0; index < udf.Parameters.Length; index++) {
                    newUdf.Parameters[index] = udf.Parameters[index];
                }
                newUdf.LineNumber = udf.LineNumber;
                newUdf.ClassName = udf.ClassName;
                newUdf.Value = udf.Value;
                newUdf.ParserFactory = udf.ParserFactory;

                return newUdf;
            }
            if (fn != null && fn is ContextFuncNode) {
                ((ContextFuncNode)fn).Context = this.Context;
            }

            return fn;
        }
    }
}
